import Vue from 'vue'
import VueRouter from 'vue-router'

// 保存原始的push方法
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [{
    path: '',
    name: 'login',
    component: () => import("../views/Login.vue")
  },
  {
    path: '/home',
    name: 'home',
    component: () => import("../views/Home.vue"),
    children: [{
        path: 'banner',
        name: 'banner',
        component: () => import("../views/pages/banner.vue")
      },
      {
        path: 'users',
        name: 'users',
        isAuth: true,
        component: () => import("../views/pages/users.vue")
      },
      {
        path: 'apply',
        name: 'apply',
        component: () => import("../views/pages/apply.vue")
      },
      {
        path: 'address',
        name: 'address',
        component: () => import("../views/pages/address.vue")
      },
      {
        path: 'order',
        name: 'order',
        component: () => import("../views/pages/order.vue")
      },
      {
        path: 'notice',
        name: 'notice',
        isAuth: false,
        component: () => import("../views/pages/notice.vue")
      },
      {
        path: 'suggest',
        name: 'suggest',
        component: () => import("../views/pages/suggest.vue")
      },
      {
        path: 'admin',
        name: 'admin',
        component: () => import('@/views/pages/admin.vue')
      }
    ]
  }


]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // 如果要访问的是登录页，直接放行
  if (to.name === 'login') {
    next()
  } else {
    const token = sessionStorage.getItem('token')
    if (token) {
      next()
    } else {
      // 如果没有token，弹出提示框告知用户需要先登录
      window.alert('请先登录')
      // 用户点击确定后，跳转到登录页
      next({ name: 'login' })
    }
  }
});

export default router